package com.woniu.smallmedical.controller;

import com.woniu.smallmedical.entity.PageBean;
import com.woniu.smallmedical.entity.ResponseResult;
import com.woniu.smallmedical.entity.User;
import com.woniu.smallmedical.server.UserServer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@CrossOrigin
@RestController

public class UserController {

	@RequestMapping("/login")
	public ResponseResult login(@RequestBody User user, Model model, HttpSession session) {
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
			User userSession = (User) session.getAttribute("user");
			System.out.println("权限"+userSession);
			if(userSession.getStatus()==3){
				return new ResponseResult(null,400,"你已离职，不能登录");
			}else if(userSession.getStatus()==4){
				return new ResponseResult(null,400,"不能登录");
			}
			else {
				return new ResponseResult(userSession, 200, "登录成功");
			}
		} catch (UnknownAccountException e) {
			model.addAttribute("msg", "账号不存在");
			return new ResponseResult(null, 400, "账号不存在");
		} catch (IncorrectCredentialsException e) {
			model.addAttribute("msg", "密码错误");
			return new ResponseResult(null, 400, "密码错误");
		} catch (AuthenticationException e) {
			e.printStackTrace();
			model.addAttribute("msg", "认证失败");
			return new ResponseResult(null, 400, "认证失败");
		}catch (NullPointerException n)
		{
			return  new ResponseResult(null,400,"登录失败，请检查账号密码");
		}
	}

	//查询所有用户并分页
	@RequestMapping("/userList")
	public ResponseResult<PageBean<User>> getUserPage(@RequestBody PageBean page) {
//		List<User> users = userServer.getUserPage(page.getPageSize(),page.getPageIndex());
		PageBean<User> pageBean = new PageBean<>();
		pageBean.setPageSize(page.getPageSize());
		pageBean.setPageIndex(page.getPageIndex());
		pageBean.setPageUrl(page.getPageUrl());

		if (page.getPageUrl() != null || page.getPageUrl() != "") {
			pageBean.setPageBeanList(userServer.getUserPage(pageBean.getPageSize(), pageBean.getPageIndex(), pageBean.getPageUrl()));
		}
		if (page.getPageUrl() == null || page.getPageUrl() == "") {
			pageBean.setPageBeanList(userServer.getUserPageNoQuery(pageBean.getPageSize(), pageBean.getPageIndex()));
//			pageBean.setPageBeanList(userServer.getAllUsers());
		}
		pageBean.setTotalRecord(userServer.getCounts());
		return new ResponseResult<PageBean<User>>(pageBean, 200, "ok！");

//		查询所有用户
//			List<User> getAllUsers = userServer.getAllUsers();
//
//		return  new ResponseResult(getAllUsers,200,"ok");
	}

	//	查询登录用户信息
	@RequestMapping("/edituser")
	public ResponseResult getUser(User user) {
		User editUser = userServer.getUser(user.getUsername());
		return new ResponseResult(editUser, 200, "ok");
	}

	@Autowired
	UserServer userServer;

	@GetMapping("/getDoctorByDid/{did}")
	public ResponseResult getDoctorByDid(@PathVariable int did) {
		System.out.println("通过科室和状态查询该科室下的所有医生(只查询状态为1（在岗）&2（休假）)");
		List<User> doctorsByDid = userServer.getDoctorByDid(did);
		return new ResponseResult(doctorsByDid, 200, "科室！");
	}
	//修改登录用户密码
	@RequestMapping("/changePassword")
	public ResponseResult changePassword(User user, String password,String newpassword){
		int num  = userServer.changePassword(user.getUsername(),password,newpassword);
		System.out.println(num);
		if(num==1) {
			return new ResponseResult(num,200,"修改密码成功");
		}else{
			return new ResponseResult(0,400,"修改密码失败");
		}
	}
//	修改登录用户信息
	@RequestMapping("/changeUserInfo")
	public ResponseResult changeUserInfo(User user) {
		if ((user.getUsername()!="") && user.getSemail()!="" &&  user.getStel()!="" && user.getAdd()!="" && (user.getSid()!=null)) {
			int count = userServer.changeUserInfo(user.getUsername(), user.getSemail(), user.getStel(), user.getAdd(), user.getSid());
			if (count == 0) {
				return new ResponseResult(0, 400, "修改失败");
			} else {
				return new ResponseResult(count, 200, "修改成功");
			}
		}else{
			return new ResponseResult(null,400,"请确认输入信息是否正确");
		}
	}

//	增加新员工
	@RequiresPermissions("userList:insert")
	@RequestMapping("/addUser")
	public ResponseResult addUser(User user) {
		System.out.println(user);
		try {
			int count = userServer.addUser(user.getUsername(), user.getSnum(),user.getSage(), user.getSex(), user.getSemail(), user.getStel(), user.getAdd(), user.getDid(), user.getRid());
			if(count==1) {
				return new ResponseResult(count,200,"新增员工‘"+user.getUsername()+"’成功！");
			}else{
				return new ResponseResult(null,400,"新增员工失败");
			}
		}catch (NullPointerException n){
			return new ResponseResult(null,500,"请输入完整信息！");
		}

	}
//	修改员工列表中的员工信息
	@RequestMapping("/changeUserListInfo")
	public ResponseResult changeUserListInfo(User user){
		System.out.println(user);
		try {
		int count = userServer.changeUserListInfo(user);
			if (count == 0) {
				return new ResponseResult(0, 400, "修改失败");
			} else {
				return new ResponseResult(count, 200, "修改成功");
			}
		}catch (NullPointerException n){
			return new ResponseResult(null,400,"请确认输入信息是否正确");
		}

	}
	//		删除员工（更改状态值为4）
	@RequestMapping("/deleteUser")
	public ResponseResult deleteUser(User user){
		System.out.println(user.getSid());
		int count = userServer.deleteUser(user.getSid());
		return new ResponseResult(count,200,"删除成功");
	}

	@GetMapping("/getDoctors")
	public ResponseResult getDoctors(){
		List<User> doctors= userServer.getDoctors();
		return new ResponseResult(doctors,200,"医生！");
	}
//	退出页面
	@RequestMapping("/loginOut")
	public ResponseResult loginOut(HttpServletRequest request){
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		System.out.println("...."+user);
		if(user != null){
			session.removeAttribute("user");
			return new ResponseResult(null,200,"退出成功");
		}
		return new ResponseResult(null,400,"shibai ");
	}
}
